import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_09_game/base/controller/base_controller.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/config/app_config.dart';
import 'package:flutter_09_game/config/app_routes.dart';
import 'package:flutter_09_game/config/history_route_ovserver.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/http/http_export.dart';
import 'package:flutter_09_game/manager/ws_manager.dart';
import 'package:flutter_09_game/pages/game/game_detail/game_detail_page/game_detail_page_view.dart';
import 'package:flutter_09_game/pages/game/game_detail/game_detail_transfer/game_detail_transfer_view.dart';
import 'package:flutter_09_game/pages/game/game_detail/models/model_game_round.dart';
import 'package:flutter_09_game/pages/game/game_detail/models/model_game_round_wallet.dart';
import 'package:flutter_09_game/pages/game/game_detail/models/model_game_ws.dart';
import 'package:flutter_09_game/pages/home/home_gameplay_tutorial/home_gameplay_tutorial_list/home_gameplay_tutorial_list_view.dart';
import 'package:flutter_09_game/pages/home/home_gameplay_tutorial/home_gameplay_tutorial_list/model_game_active.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/user/model/model_user_wallet.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/utils/sound/sound_manager.dart';
import 'package:flutter_09_game/utils/utils_other.dart';
import 'package:flutter_09_game/widgets/dialog/common_normal_sheet.dart';
import 'package:flutter_09_game/widgets/tab/common_tab_bar_page.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:wakelock_plus/wakelock_plus.dart';

class GameDetailLogic extends BaseController
    with GetTickerProviderStateMixin, WidgetsBindingObserver {
  int gameId = Get.arguments['id'];
  String name = Get.arguments?['name'] ?? "";

  List<ModelGameActive> ruleActives = [];

  Rx<ModelGameRound> gameRoundRx = ModelGameRound().obs;
  int gameCount = 60; //游戏倒计时

  Rxn<ModelGameRoundHistory> rightHistoryRx = Rxn();
  Rxn<ModelGameRoundHistory> leftBetOptionRx = Rxn();
  Rxn<ModelGameRoundHistory> rightBetOptionRx = Rxn();

  RxList<ModelGameRoundMyHistory> myHistoryRx = RxList();
  Timer? _circulationTimer;
  RxBool soundRx = false.obs;

  RxBool proShowBetRx = false.obs;

  TabController? tabController;
  List<CommonTabModel> tabData = [
    // CommonTabModel(
    //   view: GameDetailTransferPage(
    //     gameLogic: this,
    //   ),
    //   title: LocaleKeys.transferBet.tr,
    // ),
    // CommonTabModel(
    //   view: GameLastDigitPagePage(
    //     gameLogic: this,
    //   ),
    //   title: LocaleKeys.pageBet.tr,
    // ),
  ];

  Timer? _timer;

  // 倒计时（秒）- 用于UI显示
  RxInt countdown = 60.obs;

  // 倒计时（毫秒）- 用于精确计算
  RxInt countdownMs = 60000.obs;

  // 缓存上次显示的秒数,用于判断是否需要更新UI
  int _lastDisplaySeconds = 60;

  // 首次倒计时显示标志位（用于首次四舍五入）
  bool _isFirstCountdownDisplay = true;

  // 倒计时结束的时间戳（毫秒）- 用于基于真实时间计算剩余时间
  int? _countdownEndTimestamp;

  // 最近一次请求耗时（毫秒）
  // int lastRequestDuration = 0;

  // 动画控制器
  AnimationController? rotationAnimationController;
  Animation<double>? rotationAnimation;
  ModelGameWs? gameWs;

  // 游戏结果动画队列相关
  final Queue<ModelGameRoundHistory> _resultQueue = Queue();
  RxBool isShowingResult = false.obs;
  Rxn<ModelGameRoundHistory> currentResultRx = Rxn();
  AnimationController? resultAnimationController;
  Animation<double>? resultSlideAnimation;
  Animation<double>? resultFadeAnimation;
  Timer? _resultDisplayTimer;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    executeInitMethod(getGameInfo);
    WsManager().onConnectSuccess = (value) {
      if (value) {
        WsManager().beginGameSubscription(gameId);
      }
    };

    WsManager().onMessage = onMessage;
    clog('AppConfig.wsUrl   ${AppConfig.wsUrl}');
    clog('AppConfig.wsUrl   ${AppConfig.defaultApiConfig.websocket}');
    if (AppConfig.wsUrl.isNotEmpty) {
      WsManager().connectWs();
    } else {
      checkCanConnectWs(0);
    }
    WidgetsBinding.instance.addObserver(this);
    getSoundEnabled();
    WakelockPlus.enable();
    // 初始化结果动画控制器
    _initResultAnimationController();
  }

  onMessage(String value) {
    try {
      var data = jsonDecode(value);
      gameWs = ModelGameWs.fromJson(data);
      if (gameWs?.msgType == 2) {
        if (gameWs?.message != null) {
          ModelGameRoundHistory? roundHistory = gameRoundRx.value.history
              ?.firstWhereOrNull(
                  (item) => item.round == gameWs?.message?.round);
          if (roundHistory == null) {
            gameRoundRx.update((val) {
              val?.history?.insert(0, gameWs!.message!);
            });
          }
        }
      } else if (gameWs?.msgType == 1) {
        rightHistoryRx.value = gameWs?.message;
        // lastRequestDuration = 0;
        leftBetOptionRx.value = null;
        rightBetOptionRx.value = null;
        _startAnimation();
        Future.delayed(const Duration(milliseconds: 1200), () {
          // Future.delayed(Duration(seconds: 3),() {
          getGameDataSource(isCirculation: true);
        });
      } else if (gameWs?.msgType == 3) {
        if (gameWs?.message?.direction == 1) {
          if (leftBetOptionRx.value?.round == gameWs?.message?.round) {
            leftBetOptionRx.update((val) {
              val?.amount = (val.amount ?? 0) + (gameWs?.message?.amount ?? 0);
            });
          } else {
            leftBetOptionRx.value = gameWs?.message;
          }
        } else {
          if (rightBetOptionRx.value?.round == gameWs?.message?.round) {
            rightBetOptionRx.update((val) {
              val?.amount = (val.amount ?? 0) + (gameWs?.message?.amount ?? 0);
            });
          } else {
            rightBetOptionRx.value = gameWs?.message;
          }
        }
      } else if (gameWs?.msgType == 8) {
        // 游戏结果消息
        if (gameWs?.message != null) {
          addResultToQueue(gameWs!.message!);
        }
      }
    } catch (_) {
      clog('dasldjlkasdjlksa');
    }
  }

  checkCanConnectWs(int count) {
    if (count < (AppConfig.defaultApiConfig.websocket ?? []).length) {
      WsManager().checkCanConnect(
          url: (AppConfig.defaultApiConfig.websocket ?? [])[count],
          onConnectSuccess: (value) {
            if (value == true) {
              AppConfig.wsUrl =
                  (AppConfig.defaultApiConfig.websocket ?? [])[count];
              WsManager().connectWs();
            } else {
              count++;
              checkCanConnectWs(count);
            }
          });
    }
  }

  initializedAnimation() {
    // 使用准确的倒计时时间初始化动画控制器
    // int accurateCountdown =
    //     UtilsOther.getGameDuration(gameRoundRx.value.latest?.game?.type);

    // 初始化动画控制器
    rotationAnimationController = AnimationController(
      duration: Duration(seconds: gameCount),
      vsync: this,
    );
    // rotationAnimationController
    // rotationAnimationController?.value = 1;
    // rotationAnimationController.
    // rotationAnimation.
    // 创建进度动画，从0到1
    rotationAnimation = Tween<double>(
      begin: 0.0, // 开始进度
      end: 1.0, // 结束进度（完整圆弧）
    ).animate(CurvedAnimation(
      parent: rotationAnimationController!,
      curve: Curves.linear,
    ));
    // rotationAnimation.value
  }

  /// 初始化结果动画控制器
  void _initResultAnimationController() {
    resultAnimationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );

    // 下滑动画：从 -100.w 到 88.w
    resultSlideAnimation = Tween<double>(
      begin: -40.0,
      end: 0.0,
    ).animate(CurvedAnimation(
      parent: resultAnimationController!,
      curve: Curves.easeOut,
    ));

    // 淡入淡出动画
    resultFadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: resultAnimationController!,
      curve: Curves.easeIn,
    ));
  }

  @override
  void onClose() {
    _stopTimer();
    tabController?.dispose();
    rotationAnimationController?.dispose();
    _disposeResultAnimation();
    super.onClose();

    WsManager().stopGameSubscription();
    Future.delayed(const Duration(milliseconds: 300), () {
      WsManager().disconnect();
    });
    WidgetsBinding.instance.removeObserver(this);
    WakelockPlus.disable();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    clog('[GameLastDigitLogic] 应用生命周期状态变化: $state');

    if (state == AppLifecycleState.resumed) {
      // LoadingUtils.showToast('应用回到前台，检查WebSocket连接状态');
      clog('[GameLastDigitLogic] 应用回到前台，检查WebSocket连接状态');
      _checkAndReconnectWebSocket();
    }
  }

  /// 检查并重连WebSocket
  void _checkAndReconnectWebSocket() {
    if (!WsManager().isConnected) {
      // LoadingUtils.showToast('WebSocket未连接，开始重连');
      clog('[GameLastDigitLogic] WebSocket未连接，开始重连');
      WsManager().connectWs();
    } else {
      // LoadingUtils.showToast('WebSocket已连接，无需重连');
      clog('[GameLastDigitLogic] WebSocket已连接，无需重连');
    }
    getGameInfo(isFirst: false);
  }

  Future getGameInfo({bool isFirst = true}) async {
    // 记录请求开始时间
    final startTime = DateTime.now();

    HttpResponse response = await HttpManager().get(
      API.getGameRoundLatest,
      // fromJson: ModelGameRound.fromJson,
      params: {
        'game_id': gameId,
        'symbol': AppUserManager().currentWalletRx.value.symbol,
      },
    );

    // 计算请求耗时
    final endTime = DateTime.now();
    int lastRequestDuration = endTime.difference(startTime).inMilliseconds;
    clog('getGameInfo 请求耗时: ${lastRequestDuration}ms', tag: 'GameTiming');

    if (response.isSuccess) {
      gameRoundRx.value = ModelGameRound.fromJson(response.data);
      if (isFirst) {
        tabData.add(CommonTabModel(
          view: GameDetailTransferPage(
            gameLogic: this,
          ),
          title: LocaleKeys.transferBet.tr,
        ));
        if (gameRoundRx.value.forbidBetConfig != true) {
          tabData.add(CommonTabModel(
            view: GameLastDigitPagePage(
              gameLogic: this,
            ),
            title: LocaleKeys.pageBet.tr,
          ));
        }
        tabController = TabController(
            length: tabData.length,
            vsync: this,
            initialIndex: tabData.length - 1);
        gameCount =
            UtilsOther.getGameDuration(gameRoundRx.value.latest?.game?.type);
        initializedAnimation();
      }

      // clog('游戏数据获取成功');

      for (var item in (gameRoundRx.value.betAmount ?? [])) {
        if (item.direction == 1) {
          leftBetOptionRx.value = ModelGameRoundHistory()
            ..amount = item.amount
            ..round = gameRoundRx.value.latest?.round;
          // clog('ddaksdkasjd   ${gameRoundRx.value.betAmount}');
        } else if (item.direction == 2) {
          rightBetOptionRx.value = ModelGameRoundHistory()
            ..amount = item.amount
            ..round = gameRoundRx.value.latest?.round;
        }
      }

      rightHistoryRx.value = ModelGameRoundHistory.fromJson(
          gameRoundRx.value.latest?.toJson() ?? {});

      _startAnimation(
          currentServerTime: gameRoundRx.value.currentServerTime,
          requestDurationMs: lastRequestDuration);
      getGameDataSource();
      // checkShowStopGame();
    }
  }

  _stopTimer() {
    _timer?.cancel();
    _timer = null;
  }

  /// 查看更多历史记录
  void viewMoreHistory() {
    // TODO: 跳转到历史记录页面
    Get.toNamed(AppRoutes.gameDrawResultsPage, arguments: {'id': gameId});
    // LoadingUtils.showToast('查看更多历史记录');
  }

  /// 查看更多投注记录
  void viewMoreBetHistory() {
    // TODO: 跳转到投注记录页面
    Get.toNamed(AppRoutes.gameMineResultsPage, arguments: {'id': gameId});
    // LoadingUtils.showToast('查看更多投注记录');
  }

  /// 查看更多投注记录
  void viewMoreRecordHistory() {
    // TODO: 跳转到投注记录页面
    Get.toNamed(AppRoutes.profileBetRecordPage);
    // LoadingUtils.showToast('查看更多投注记录');
  }

  // profileBetRecordPage

  Future getGameDataSource({bool isCirculation = false}) async {
    HttpResponse response = await HttpManager().get(
      API.getGameRoundJoinMine,
      // fromJson: .fromJson,
      params: {'page': 1, 'size': 10, 'game_id': gameId},
      // fromJson: ModelGameRoundMyHistory.fromJson
    );

    if (response.isSuccess) {
      List<ModelGameRoundMyHistory> data = List<ModelGameRoundMyHistory>.from(
          (response.data['list'] as List)
              .map((e) => ModelGameRoundMyHistory.fromJson(e)));
      myHistoryRx.value = data;

      // ModelGameRoundWallet
      List<ModelGameRoundWallet> wallets = List<ModelGameRoundWallet>.from(
          (response.data['wallets'] as List)
              .map((e) => ModelGameRoundWallet.fromJson(e)));
      for (ModelGameRoundWallet item in wallets) {
        ModelUserWallet? appWallet = AppUserManager()
            .walletList
            .firstWhereOrNull((val) => val.symbol == item.symbol);
        appWallet?.balance = item.balance;
        if (item.symbol == AppUserManager().currentWalletRx.value.symbol) {
          clog('dalksjdlkasjd');
          AppUserManager().currentWalletRx.update((val) {
            val?.balance = item.balance;
          });
        }
      }

      if (isCirculation) {
        // data = List<T>.from(
        //     (response.data['list'] as List).map((e) => fromJson.call(e)));
        // AppUserManager().loadWalletData();
        List<ModelGameRoundMyHistory> rows = myHistoryRx.where((item) {
          return (item.status == 1 || item.status == 2) &&
              item.round != rightHistoryRx.value?.round;
        }).toList();
        _circulationTimer?.cancel();
        _circulationTimer = null;
        if (rows.isNotEmpty) {
          _circulationTimer =
              Timer.periodic(const Duration(milliseconds: 500), (t) {
            getGameDataSource(isCirculation: true);
          });
        }
      }
    }
  }

  Future getGameActive() async {
    HttpResponse response = await HttpManager().get(
      API.getGameActive,
      fromJson: ModelGameActive.fromJson,
    );
    if (response.isSuccess) {
      ruleActives = response.data;
    }
  }

  showRuleSheet() async {
    if (ruleActives.isEmpty) {
      await getGameActive();
    }
    ModelGameActive? gameActive =
        ruleActives.firstWhereOrNull((item) => item.game?.id == gameId);

    if (gameActive != null) {
      CommonNormalSheet(
        title:
            "【${gameActive.game?.name ?? ""}】${LocaleKeys.gameplayTutorial.tr}",
        child: SizedBox(
          height: 500.h,
          child: HomeGameplayTutorialListPage(
            type: (gameActive.game?.id ?? '').toString(),
            gameActive: gameActive,
          ),
        ),
      ).show();
    }
  }

  /// 获取当前音效开关状态
  getSoundEnabled() async {
    soundRx.value = await SoundManager().getSoundEnabled();
    clog('当前音效开关状态: ${soundRx.value}');
  }

  /// 切换音效开关状态
  Future<void> toggleSoundEnabled() async {
    soundRx.value = await SoundManager().toggleSoundEnabled();
    clog('音效状态切换为: ${soundRx.value}');
  }

  /// 计算准确的倒计时时间（毫秒）
  /// 基于服务器创建时间和游戏持续时间计算精确的剩余时间
  /// 计算方式：游戏持续时间 - (当前时间 - 创建时间)
  /// 返回值：剩余毫秒数
  int calculateAccurateCountdownMs(String? createdAt, int? type,
      {int requestDurationMs = 0, String? currentServerTime}) {
    try {
      // 获取游戏持续时间（毫秒）
      int gameDurationMs = gameCount * 1000;

      if (createdAt == null || createdAt.isEmpty) {
        clog('创建时间为空，使用默认游戏持续时间: ${gameDurationMs}ms');
        return gameDurationMs;
      }

      // 解析ISO 8601时间格式并转换为时间戳（毫秒）
      int serverTimeMs =
          DateTime.parse(createdAt).toLocal().millisecondsSinceEpoch;

      int currentTimeMs = currentServerTime == null
          ? DateTime.now().toLocal().millisecondsSinceEpoch
          : DateTime.parse(currentServerTime).toLocal().millisecondsSinceEpoch;

      // 补偿网络延迟
      if (requestDurationMs > 0) {
        currentTimeMs += requestDurationMs;
      }

      // 计算已过去的毫秒数
      int elapsedMs = currentTimeMs - serverTimeMs;

      // 计算剩余毫秒数
      int remainingMs = gameDurationMs - max(0, elapsedMs);
      if (remainingMs <= 0) {
        remainingMs = gameDurationMs;
      }

      clog(
          '准确倒计时计算(毫秒): 创建时间=$createdAt, 游戏持续时间=${gameDurationMs}ms, 已过去=${elapsedMs}ms, '
          '网络延迟=${requestDurationMs}ms, 调整后剩余=${remainingMs}ms (${(remainingMs / 1000.0).toStringAsFixed(1)}秒)');

      // 确保倒计时不为负数
      return remainingMs > 0 ? remainingMs : 0;
    } catch (e) {
      clog('倒计时计算出错: $e，使用默认游戏持续时间');
      // 出错时返回默认的游戏持续时间（毫秒）
      return gameCount * 1000;
    }
  }

  String getReceiveAddress() {
    var value = gameRoundRx.value.latest?.game?.gameSetting
        ?.firstWhereOrNull((item) =>
            item.key ==
            (AppUserManager().currentWalletRx.value.symbol?.toUpperCase() ==
                    "TRX"
                ? 'TRXReceiveAddressKey'
                : "USDTReceiveAddressKey"))
        ?.value;
    return value.toString();
  }

  void _startAnimation({int requestDurationMs = 0, String? currentServerTime}) {
    rotationAnimationController?.reset();
    _stopTimer();

    // int gameDuration =
    //     UtilsOther.getGameDuration(rightHistoryRx.value?.game?.type);
    int gameDurationMs = gameCount * 1000;

    // 使用准确的倒计时时间（毫秒）替换固定的gameCount（已包含网络延迟补偿）
    int accurateCountdownMs = calculateAccurateCountdownMs(
        rightHistoryRx.value?.createdAt,
        // gameRoundRx.value.currentServerTime,
        rightHistoryRx.value?.game?.type,
        requestDurationMs: requestDurationMs,
        currentServerTime: currentServerTime);

    // 初始化毫秒倒计时
    countdownMs.value = accurateCountdownMs;

    // 初始化秒数显示
    _lastDisplaySeconds = (accurateCountdownMs / 1000).round();
    countdown.value = _lastDisplaySeconds;

    // 计算动画进度
    double progress =
        (gameDurationMs - accurateCountdownMs) / gameDurationMs.toDouble();

    clog(
        '动画进度计算: 倒计时=${accurateCountdownMs}ms (${_lastDisplaySeconds}s), 进度=${progress.toStringAsFixed(3)}',
        tag: 'GameTiming');

    rotationAnimationController?.value = progress;
    rotationAnimationController?.forward();

    proShowBetRx.value = false;
    routeHistoryObserver.removeName('checkShowStopGame');

    // 计算并保存倒计时结束的时间戳
    _countdownEndTimestamp =
        DateTime.now().millisecondsSinceEpoch + accurateCountdownMs;

    clog('倒计时初始化: 剩余=${accurateCountdownMs}ms, 结束时间戳=${_countdownEndTimestamp}',
        tag: 'GameTiming');

    // 重置首次显示标志位
    _isFirstCountdownDisplay = true;

    // 启动高频定时器（每100ms执行一次）
    _timer = Timer.periodic(const Duration(milliseconds: 100), (timer) {
      // 基于时间戳重新计算剩余毫秒数（解决息屏后倒计时不准的问题）
      int currentTimestamp = DateTime.now().millisecondsSinceEpoch;
      int remainingMs = max(_countdownEndTimestamp! - currentTimestamp, 0);

      // 更新毫秒倒计时
      countdownMs.value = remainingMs;
      // (countdownMs.value / 1000).ceil();
      // clog(
      //     'remainingMs  ${remainingMs}   ${(countdownMs.value / 1000).round()}');
      // // 首次显示：使用向上取整（ceil）
      // if (_isFirstCountdownDisplay) {
      //   int ceiledSeconds = (countdownMs.value / 1000).ceil();
      //   countdown.value = ceiledSeconds;
      //   _lastDisplaySeconds = (countdownMs.value / 1000).floor();
      //   _isFirstCountdownDisplay = false;
      //
      //   clog('倒计时首次显示: ${countdownMs.value}ms → 显示 ${ceiledSeconds}s',
      //       tag: 'GameTiming');
      //
      //   // 首次显示也需要检查禁投
      //   if (checkForbidBet()) {
      //     clog('触发禁投检查');
      //     checkShowStopGame();
      //   }
      // } else {
      //   // 后续更新：基于整秒边界（千位数变化）
      int currentSeconds = (countdownMs.value / 1000).round();

      // 只在千位数变化时更新UI和检查禁投
      if (currentSeconds != _lastDisplaySeconds) {
        _lastDisplaySeconds = currentSeconds;
        countdown.value = currentSeconds;
        if (checkForbidBet()) {
          clog('触发禁投检查');
          checkShowStopGame();
        }
        clog('倒计时更新: ${countdownMs.value}ms → 显示 ${currentSeconds}s',
            tag: 'GameTiming');

        // 检查是否需要禁止投注
      }
      // }

      // 倒计时结束
      if (countdownMs.value <= 0) {
        _stopTimer();
        routeHistoryObserver.removeName('checkShowStopGame');
        clog('倒计时结束', tag: 'GameTiming');
      }
    });
  }

  checkShowStopGame() {
    if (Get.currentRoute == AppRoutes.gameDetailPage &&
        tabController?.index == 1 &&
        !routeHistoryObserver.history
            .map((rou) => rou.settings.name)
            .contains(CommonNormalSheet.name)) {
      proShowBetRx.value = true;
      showStopGame();
    }
  }

  showStopGame() {
    routeHistoryObserver.removeName('checkShowStopGame');
    // CommonNormalSheet
    // FocusManager.instance.primaryFocus?.unfocus();

    Get.dialog(
      Center(
          child: Container(
        width: 300.w,
        padding: EdgeInsets.all(24.w),
        decoration: BoxDecoration(
            color: AppColor.navBgColor,
            borderRadius: BorderRadius.circular(12.w)),
        // alignment: Alignment.center,
        child: Text(
          LocaleKeys.betClosedTip.tr,
          textAlign: TextAlign.center,
          style: TextStyle(
              fontWeight: FontWeight.w500,
              fontSize: 14.sp,
              color: AppColor.textPrimary.withOpacity(0.94)),
        ),
      )),
      transitionDuration: Duration.zero,
      name: 'checkShowStopGame',
    );
  }

  bool checkForbidBet() {
    int? type = rightHistoryRx.value?.game?.type;
    int remainingMs = countdownMs.value;

    if (type == 2 ||
        type == 3 ||
        type == 4 ||
        type == 5 ||
        type == 6 ||
        type == 7) {
      // 剩余时间 <= 10秒（10000毫秒）
      if (remainingMs > 0 &&
          remainingMs <= 3500 &&
          proShowBetRx.value == false) {
        return true;
      }
    }

    // if (type == 2 || type == 3) {
    //   // 剩余时间 <= 10秒（10000毫秒）
    //   if (remainingMs > 0 &&
    //       remainingMs <= 10000 &&
    //       proShowBetRx.value == false) {
    //     return true;
    //   }
    // } else if (type == 4) {
    //   // 剩余时间 <= 3秒（3000毫秒）
    //   if (remainingMs > 0 &&
    //       remainingMs <= 3000 &&
    //       proShowBetRx.value == false) {
    //     return true;
    //   }
    // } else if (type == 5) {
    //   // 剩余时间 <= 4秒（4000毫秒）
    //   if (remainingMs > 0 &&
    //       remainingMs <= 4000 &&
    //       proShowBetRx.value == false) {
    //     return true;
    //   }
    // }

    return false;
  }

  /// 添加结果到队列
  void addResultToQueue(ModelGameRoundHistory result) {
    _resultQueue.add(result);
    clog(
        '添加游戏结果到队列: round=${result.round}, isWin=${result.isWin}, 队列长度=${_resultQueue.length}');

    // 如果当前没有正在显示的动画，立即处理
    if (!isShowingResult.value) {
      _processNextResult();
    }
  }

  /// 处理队列中的下一个结果
  void _processNextResult() {
    if (_resultQueue.isEmpty) {
      isShowingResult.value = false;
      currentResultRx.value = null;
      return;
    }

    isShowingResult.value = true;
    currentResultRx.value = _resultQueue.removeFirst();
    clog(
        '开始显示游戏结果: round=${currentResultRx.value?.round}, isWin=${currentResultRx.value?.isWin}');

    _showResultAnimation();
  }

  /// 显示结果动画
  void _showResultAnimation() {
    // 重置动画
    resultAnimationController?.reset();

    // 开始下滑动画（300ms）
    resultAnimationController?.forward();

    // 2秒后开始淡出
    _resultDisplayTimer?.cancel();
    _resultDisplayTimer = Timer(const Duration(milliseconds: 2000), () {
      // 淡出动画（300ms）
      resultAnimationController?.reverse().then((_) {
        // 动画结束后处理下一个
        _processNextResult();
      });
    });
  }

  /// 清理结果动画资源
  void _disposeResultAnimation() {
    _resultDisplayTimer?.cancel();
    _resultDisplayTimer = null;
    resultAnimationController?.dispose();
    resultAnimationController = null;
    _resultQueue.clear();
  }
}
